package v1

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/minio/minio-go/v7"
	"go-admin/global"
	myMinio "go-admin/global/minio"
	"go-admin/internal/service"
	"go-admin/pkg/app"
	"go-admin/pkg/util"
	"os"
)

type Upload struct {
	FileName    string // 文件名称
	FileSize    int64  // 文件大小
	ContentType string // 文件类型
}

func NewUpload() Upload {
	return Upload{}
}

// 文件上传
func (u *Upload) Upload(c *gin.Context) {
	response := app.NewResponse(c)
	svc := service.New(c.Request.Context())
	fileName, contentType, flag, rd := svc.GetFileInfo(c)
	u.FileName = fileName
	u.ContentType = contentType
	if err := svc.SaveFile(rd, flag, "./temp/"+u.FileName); err != nil {
		return
	}
	uploadInfo, err := myMinio.MinioClient.FPutObject(c.Request.Context(), global.MinioSetting.BucketName, u.FileName, "./temp/"+u.FileName, minio.PutObjectOptions{ContentType: u.ContentType, PartSize: 1024 * 1024 * 5})
	if err != nil {
		return
	}
	// 判断文件是否存在
	if exist := util.Exist("./temp/" + u.FileName); exist {
		// 删除文件
		if err := os.Remove("./temp/" + u.FileName); err != nil {
		}
	}
	m := make(map[string]interface{})
	m["url"] = fmt.Sprintf("http://127.0.0.1:9000/%s/%s", uploadInfo.Bucket, uploadInfo.Key)
	response.Ok(app.WithData(m))
	return
}
